from module.aaa_example import example
from flask.signals import _signals
from flask import render_template
 

# 1 定义信号,signal_demo1 is signal_demo2 true,它们是一样的
# 也可以不指定name,则是唯一的
signal_demo1 = _signals.signal("signal_demo")
signal_demo2 = _signals.signal("signal_demo")
 
# 2 写个函数,此方法可以在其他类中设定
def signal_callfun1(arg1):
    print("signal_callfun1:",arg1)

def signal_callfun2(arg1):
    print("signal_callfun2:",arg1)

# 通过装饰器来订阅
@signal_demo2.connect
def signal_callfun3(arg1):
    print("signal_callfun3:",arg1)
 
# 3 在其他类或文件里绑定信号,connect()方法接收一个可选参数sender，可用于接收指定发布者的参数。
signal_demo1.connect(signal_callfun1,sender="2")
# 可以绑定多个函数,会一起被调用
signal_demo1.connect(signal_callfun2)

# 4 发生信号
@example.route('/signal')
def send_signals():
    # 检查信号是否有订阅者
    if bool(_signals.signal('signal_demo').receivers):
        for i in ["1","2","3"]:
            signal_demo1.send(i)
            print("~~~~~~~~~~~~~~~")
            signal_demo2.send(i)
            print("~~~~~~~~~~~~~~~")
    return render_template("/aaa_example/index.html")

# 5 解绑信号函数signal_callfun1
# signal_demo.disconnect(signal_callfun1)